<template>
  <div class="users">
    <!-- 面包屑 -->
    <!-- <berate leve1="用户管理" leve2="用户列表"></berate> -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <br />
    <!-- 搜索框 -->
    <el-card class="box-card">
      <el-form>
        <el-input v-model="queryInfo.query" placeholder="请输入内容">
          <el-button @click="chaHandel" slot="append" icon="el-icon-search"></el-button>
        </el-input>
        <el-button class="tj" type="primary" @click="isAddUser=true">添加</el-button>

        <!-- 用户表格 -->

        <el-table class="a" :data="list" border style="width: 100%">
          <el-table-column type="index" label="#" width="80"></el-table-column>
          <el-table-column prop="username" label="姓名" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch @change="changeStatus(scope.row)" v-model="scope.row.mg_state"></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="edit(scope.row)" type="primary" icon="el-icon-edit"></el-button>
              <el-button @click="del(scope.row.id)" type="danger" icon="el-icon-delete"></el-button>
              <el-button @click="fenHandel(scope.row)" type="warning" icon="el-icon-setting"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10]"
        :page-size="1"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户弹窗 -->
    <el-dialog title="添加用户" :visible.sync="isAddUser">
      <el-form :ref="addData" :model="addData" :rules="addUserDiaRules">
        <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
          <el-input v-model="addData.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
          <el-input v-model="addData.password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="addData.email" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="addData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddUser = false">取 消</el-button>
        <el-button type="primary" @click="addUserConfirm(addData)">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户弹窗 -->

    <el-dialog title="编辑用户" :visible.sync="isCompile">
      <el-form ref="EsUserDia" :model="addData" :rules="addUserDiaRules">
        <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
          <el-input disabled v-model="addData.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="addData.email" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="addData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isCompile = false">取 消</el-button>
        <el-button type="primary" @click="edConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户角色 -->
    <el-dialog title="分配角色" :visible.sync="isRouter">
      <div class="userinfo">
        <p>当前用户：{{user.user}}</p>
        <p>当前角色：{{user.role}}</p>
      </div>
      <el-form>
        <el-form-item label="分配新角色">
          <el-select v-model="currrentRoleId" placeholder="请选择角色">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isRouter = false">取 消</el-button>
        <el-button type="primary" @click="getRouter">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStatus, getCompile, getUserAPI, getRoleList } from "../../http/api";

export default {
  data() {
    //手机号验证规则
    const checkMobile = (rule, value, callback) => {
      const reg = /^1(3|4|5|6|7|8|9)\d{9}$/g;
      if (!reg.test(value)) {
        return callback(new Error("手机号不合法，请输入重新手机号"));
      }
      callback();
    };
    return {
      value: true,

      addData: {
        username: "12345",
        password: "2143432",
        email: "31241@qq.com",
        mobile: "15456786778"
      },
      formLabelWidth: "120px",
      // 添加弹窗
      isAddUser: false,
      // 编辑弹窗
      isCompile: false,
      isRouter: false,
      currrentRoleId:'',
      user: {
        username:'',
        role_name:''
      },
      // 用户id
      currId: "",
      input: "",
      //   用户列表
      list: [],
      rolesList: [],

      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      //   页数
      total: 0,

      //   添加用户验证规则
      addUserDiaRules: {
        username: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 18, message: "长度在 6 到 18 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getlist();
  },
  methods: {
    async fenHandel(row) {
      console.log(row);
     
      this.isRouter = true;
      this.user={
        'user':row.username,
        'role':row.role_name,
        'id':row.id
      }
    

      // 获取角色列表
      let { data: res } = await this.$axios.get("roles");
      if ((res.meta.status != 200)) {
        return this.$message.error("获取角色失败");
      }
      this.$message.success('获取角色列表成功')
      this.rolesList = res.data;
    },
    // 提交角色列表
    async getRouter(){

       if(!this.currrentRoleId){
         return this.$message.error('请选者角色')
       }
      let { data: res } = await this.$axios.put(`users/${this.rolesList.id}/role`,{
        rid:this.currrentRoleId
      });
       if ((res.meta.status != 200)) {
        return this.$message.error("更新角色失败");
      }
      this.$message.success('更新角色成功')
this.isRouter=false
this.currrentRoleId=''
this.getlist()

     },
     

    // 打开编辑窗口
    edit(row) {
      this.isCompile = true;
      this.currId = row.id;
      this.addData = row;
    },
    // 提交修改用户信息
    edConfirm() {
      console.log(1);
      this.$refs.EsUserDia.validate(async valid => {
        if (!valid) return;
        this.$axios.put(`/users/${this.currId}`, this.addData);
        this.isCompile = false;
      });
    },

    //触发改变状态的回调
    changeStatus(row) {
      // let { id, mg_state } = row;
      // console.log("当前用户信息:", row);
      // //调用修改用户状态接口
      // const res = await getStatus(id, mg_state);
      // this.getlist();
      console.log(row);

      console.log(123);
      this.$axios.put(`users/${row.id}/state/${row.mg_state}`).then(res => {
        console.log(106, res);
        if (res.data.meta.status != 200) {
          this.message.error(res.data.meta.msg);
        }
      });
    },
    // 查询
    chaHandel() {
      this.getlist();
    },

    // 增加信息
    addUserConfirm(addData) {
      this.$refs[addData].validate(valid => {
        if (valid) {
          this.$axios.post("users", this.addData).then(res => {
            this.getlist();
          });
          this.isAddUser = false;
        } else {
          return false;
        }
      });
    },
    // 分页
    handleSizeChange(val) {
      // console.log(val);

      this.queryInfo.pagesize = val;
      this.getlist();
    },
    // 分页
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      this.getlist();
    },
    // 删除
    async del(id) {
      console.log(1);

      console.log(id);
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);

      if (res !== "confirm") {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      } else {
        await this.$axios.delete(`users/${id}`);
        this.$message({
          type: "success",
          message: "删除成功!"
        });
        this.getlist();
      }
    },

    async dele(id) {
      const res = await this.$confirm("确定删除？无法撤销！", {});
    },

    resetForm(addData) {},

    async getlist() {
      const res = await this.$axios.get("users", { params: this.queryInfo });
      // 表格数据
      this.list = res.data.data.users;
      // 分页
      this.total = res.data.data.total;

      console.log(this.list);
    }
  }
};
</script>

<style lang="scss" scoped>
.a {
  margin-top: 20px;
}
.tj {
  margin-left: 30px;
}
.el-input {
  width: 300px;
}
</style>